package com.sosee.cgfw.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.lidroid.xutils.BitmapUtils;
import com.sosee.cgfw.R;
import com.sosee.cgfw.camera.FragmentAdapter;
import com.sosee.cgfw.camera.PicFragment;
import com.sosee.cgfw.utils.LogUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Thinkpad on 2016/4/19.
 */
public class ShowYourSelfPicActivity extends FragmentActivity implements ViewPager.OnPageChangeListener {
    private ViewPager vp;
    private FragmentAdapter mAdapter;
    private List<Fragment> flist;
    private RelativeLayout fl_new;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chosepic);
        initView();
    }


    public void click(View view){
        getPhoto();
    }





    public void initView(){
        fl_new= (RelativeLayout) findViewById(R.id.rl_new);
        vp= (ViewPager) findViewById(R.id.vp);
        mAdapter=new FragmentAdapter(getSupportFragmentManager());
        flist=new ArrayList<Fragment>();
        PicFragment f1=new PicFragment();
        Bundle bundle=new Bundle();
        bundle.putString("flag", "0");
        f1.setArguments(bundle);
        PicFragment f2=new PicFragment();
        Bundle b2=new Bundle();
        b2.putString("flag", "1");
        f2.setArguments(b2);

        PicFragment f3=new PicFragment();
        Bundle b3=new Bundle();
        b3.putString("flag","2");
        f3.setArguments(b3);
        flist.add(f1);
        flist.add(f2);
        flist.add(f3);
        mAdapter.setList(flist);
        vp.setAdapter(mAdapter);
        vp.setOnPageChangeListener(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    //将界面上的控件转化为图片
    public void getPic(String picPath) {

        final Bitmap bmp = Bitmap.createBitmap(fl_new.getWidth(), fl_new.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmp);
        fl_new.draw(canvas);
        final String photoUrl = picPath;//换成自己的图片保存路径
        final File file = new File(photoUrl);
        new Thread() {
            @Override
            public void run() {

                boolean bitMapOk = false;
                try {
                    bitMapOk = bmp.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
                } catch (FileNotFoundException e) {
                }
                if (bitMapOk) {
                }

            }
        }.start();

        //通知系统更新相册  使用户能够通过相册访问自拍图片
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private BitmapUtils bitmapUtils;
    private String imgUrl;//从相册选择的图片的路劲；
    //打开系统相册  "image/*"
    //外网暂时未开放此功能
    private int RESULT_LOAD_IMAGE=0;
    public void getPhoto(){
        Intent intent = new Intent(
                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, RESULT_LOAD_IMAGE);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            LogUtils.log_E("图片路劲：==" + picturePath);


            ImageView imageView = (ImageView) findViewById(R.id.ig);
            Bitmap bit= BitmapFactory.decodeFile(picturePath);
            imgUrl=picturePath;
            bit=small(bit);
            imageView.setImageDrawable(resizeImage(bit, imageView.getWidth(),imageView.getHeight()));

        }
        super.onActivityResult(requestCode, resultCode, data);
    }



    //压缩图片
    private static Bitmap small(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
        return resizeBmp;
    }
    //指定大小对图片进行压缩

    public static Drawable resizeImage(Bitmap bitmap, int w, int h)
    {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        float n=scaleHeight>scaleWidth?scaleHeight:scaleWidth;

        Matrix matrix = new Matrix();
        matrix.postScale(n, n);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return new BitmapDrawable(resizedBitmap);
    }


}
